﻿using System;
using System.Collections.Generic;
using System.Linq;
using ET;
using Marx;
using Server;

namespace Demo
{
    [ObjectSystem]
    public class PlayerCreatorAwakeSystem : AwakeSystem<PlayerCreatorComponent>
    {
        public override void Awake(PlayerCreatorComponent self)
        {
            self.Awake();
        }
    }

    public class PlayerCreatorComponent : Entity, IAwake
    {
        public List<StartSceneConfig> LogicAddress = new List<StartSceneConfig>();
        public Dictionary<int, StartSceneConfig> Id_LogicAddress = new Dictionary<int, StartSceneConfig>();

        public void Awake()
        {
            int zone = this.DomainZone();
            LogicAddress = StartConfig.Instance.Scenes.Where(i => i.ZoneId == zone && i.Type == ServerSceneType.Logic).ToList();
            foreach (var config in LogicAddress)
            {
                Id_LogicAddress.Add(config.ID, config);
            }
        }

        public StartSceneConfig GetPlayerLogic(int logicId)
        {
            return Id_LogicAddress[logicId];
        }

        public async ETTask<int> CreatePlayer(int logicId, long playerId, long agentActor, ClientAgent client)
        {
            try
            {
                var config = Id_LogicAddress[logicId];
                var req = new SSCreatePlayerRequest()
                {
                    Account = client.Account,
                    AccountId = client.AccountId,
                    PlayerId = playerId,
                    AgentActor = agentActor
                };

                var resp = await MessageHelper.CallActor(config.InstanceId, req) as SSCreatePlayerResponse;
                client.SetPlayer(playerId, resp.PlayerActor, logicId);
                return resp.Error;
            }
            catch (Exception e)
            {
                Log.Error(e);
                return ResultCode.ERR_Fail;
            }
        }
    }
}
